using UnityEngine;
using UnityEngine.UI;

public class ShopItemInteractor : MonoBehaviour
{
    public Item itemData; // 商品数据
    public Player player; // 玩家对象

    public float interactionRange = 1.0f; // 交互范围
    public GameObject interactionPromptPrefab; // 提示框预制件
    private GameObject interactionPrompt; // 提示框实例
    private Text promptText; // 提示文本

    private bool isPlayerNearby = false; // 玩家是否在交互范围内

    private void Start()
    {
        if (player == null)
        {
            player = FindObjectOfType<Player>();
            if (player == null)
            {
                Debug.LogError("Player对象未找到");
                return;
            }
        }

        // 实例化提示框预制件并设置为当前物体的子物体
        if (interactionPromptPrefab != null)
        {
            interactionPrompt = Instantiate(interactionPromptPrefab, transform);
            interactionPrompt.SetActive(false);
            promptText = interactionPrompt.GetComponentInChildren<Text>();
            if (promptText == null)
            {
                Debug.LogError("PromptText组件未找到");
                return;
            }
        }
    }

    private void Update()
    {
        if (player != null && Vector3.Distance(player.transform.position, transform.position) <= interactionRange)
        {
            if (!isPlayerNearby)
            {
                isPlayerNearby = true;
                ShowInteractionPrompt();
            }

            if (Input.GetKeyDown(KeyCode.E))
            {
                AttemptPurchase();
            }
        }
        else
        {
            if (isPlayerNearby)
            {
                isPlayerNearby = false;
                HideInteractionPrompt();
            }
        }
    }

    private void ShowInteractionPrompt()
    {
        if (interactionPrompt != null)
        {
            interactionPrompt.SetActive(true);
            promptText.text = $"按下 E 键购买 {itemData.itemName}（价格: {itemData.SalePrice} 金币）";
        }
    }

    private void HideInteractionPrompt()
    {
        if (interactionPrompt != null)
        {
            interactionPrompt.SetActive(false);
        }
    }

    private void AttemptPurchase()
    {
        if (player.gold >= itemData.SalePrice)
        {
            player.gold -= itemData.SalePrice;
            player.AddToInventory(itemData);
            Debug.Log($"购买成功: {itemData.itemName}，剩余金币: {player.gold}");
            HideInteractionPrompt();
            Destroy(gameObject);
        }
        else
        {
            Debug.Log($"金币不足，无法购买: {itemData.itemName}");
        }
    }
}
